package com.cinyi.cyds.test;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.junit.After;
import org.junit.Before;

/**
 * 多线程测试case
 * @author penghui
 *
 */
public abstract class AbstractThreadBaseCase extends BaseCase
{
    
    private ExecutorService pool = null;
    
    private Long locked = 0L ;
    
    @Before
    public void setup() {
        super.setup();
//        DbConnectionManager.getInstance().init();
//        MongoManager.getInstance().start();
//        RedisManager.getInstance().start();
    }
    
    @After
    public void destory(){
//        MongoManager.getInstance().destroy();
//        RedisManager.getInstance().destroy();
        
        if(pool != null)
            pool.shutdown();
        
        super.destory();
        
    }
    
    /**
     * 启动多线程测试
     * @param max       最大线程数
     * @param loop      线程数目
     * @param sleep     线程睡眠时间
     */
    public void runOnThread(int max,Long loop ,long sleep){
        pool = Executors.newFixedThreadPool(max, new DaemonThreadFactory());
        
        for(long i=1;i<loop;i++){
        	System.out.println("当前处理数-->"+i);
            pool.execute(createInterceptRunnable(i));
        }
        
        while(getThreadCount()>0){
            try
            {
                Thread.sleep(sleep);
            }
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }
        }
        pool.shutdown();
        
    }
    

    public abstract InterceptRunnable createInterceptRunnable(long index);

    public synchronized Long getThreadCount()
    {
        return locked ;
    }

    public synchronized void increaseCount()
    {
        this.locked ++ ;
    }
    
    public synchronized void decreaseCount()
    {
        this.locked --  ;
    }

}